package org.example.Servlet;

import org.example.Dao.DamDao;
import org.example.Entity.Dam;
import org.example.Utils.DBUtil;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;

@WebServlet("/GetUDamListServlet")
public class GetDamListServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String river = request.getParameter("river");

        Connection conn = null;
        try {
            conn = DBUtil.getConnection();
            DamDao damDao = new DamDao(conn);
            List<Dam> dams = damDao.searchDams(name, river);

            JSONArray jsonArray = new JSONArray();
            for (Dam dam : dams) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", dam.getId());
                jsonObject.put("name", dam.getName());
                jsonObject.put("river", dam.getRiver());
                jsonObject.put("capacity", dam.getCapacity());
                jsonObject.put("completeDate", dam.getCompleteDate());
                jsonArray.put(jsonObject);
            }

            response.setContentType("application/json");
            response.getWriter().write(jsonArray.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            response.sendError(500, "Internal Server Error");
        } finally {
            DBUtil.closeConnection(conn);
        }
    }
}